package com.zhangxin.easyexcelutil.util;

import com.alibaba.excel.EasyExcel;
import com.zhangxin.easyexcelutil.model.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * Created by zhangxin on 2021/1/30.
 */
public class ExcelUtil {

    /**
     * 写出Excel(单个sheet)
     *
     * @param list 导出结果
     * @param fileName  导出文件名
     * @return excel文件二进制
     */
    public static ResponseEntity<? extends Object> writeExcel(List<User> list, String fileName) {
        HttpHeaders headers = new HttpHeaders();
        try {
            // 1.导出结果判断
            if (CollectionUtils.isEmpty(list)) {
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return new ResponseEntity<>("ERROR:数据为空", headers, HttpStatus.OK);
            }

            // 2.设置媒体类型
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 3.导出文件输出
            ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
            EasyExcel.write(outByteStream, User.class).sheet().doWrite(list);

            return new ResponseEntity<>(outByteStream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            return new ResponseEntity<>("ERROR:导出失败，请重试！", headers, HttpStatus.OK);
        }

    }
}
